package com.example.idlefish.Message

import MessagePreviewAdapter
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.pojo.GoodEase
import com.example.idlefish.MyAccount.pojo.User
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.PublicModule.UserConst
import com.example.idlefish.R
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.io.Serializable

class MessageMainFragment : Fragment() {
    private val client = OkHttpClient()

    private lateinit var recyclerView: RecyclerView
    private lateinit var searchEditText: EditText
    private lateinit var searchButton: Button

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.message_main, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView = view.findViewById(R.id.recycler_message_preview)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = MessagePreviewAdapter(getInitMessageList().toMutableList())

        searchEditText = view.findViewById(R.id.edittext_message_preview_serach)
        searchButton = view.findViewById(R.id.edittext_message_preview_serach_button)

        searchButton.setOnClickListener {
            if (searchEditText.text.isNullOrEmpty())
                return@setOnClickListener
            val receiverID = searchEditText.text.toString().toInt()
            var messagePD = MessagePreviewData(
                UserConst.id.toInt(),
                receiverID,
                "Alice",
                "https://example.com/avatar/alice.jpg",
                "Bob",
                "https://example.com/avatar/alice.jpg",
                "Hello, Bob!",
                "",
                "2021-01-01 12:00:00",
                0
            )

            // 网络请求
            val gson = Gson()
            val url = NetworkSettings.HTTP + "/user/queryUserById?id=${receiverID}"
            val request = Request.Builder()
                .url(url)
                .build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful) {
                        val body = response.body?.string()
                        val jsonObject = JSONObject(body)
                        if (jsonObject.isNull("data")) {
                            requireActivity().runOnUiThread() {
                                Toast.makeText(requireContext(), "No User", Toast.LENGTH_SHORT).show()
                            }
                            return
                        }
                        val data = jsonObject.getJSONObject("data")
                        val user = gson.fromJson(data.toString(), User::class.java)
                        messagePD.receiverName = user.nickname.toString()
                        messagePD.receiverAvatar = user.avatar.toString()



                        val intent = Intent(context, MessageChatActivity::class.java)
                        var receiverID = searchEditText.text.toString()
                        if (receiverID == "") {
                            receiverID = "-1"
                        }
                        if (UserConst.avatar != null) {
                            messagePD.senderAvatar = UserConst.avatar!!
                        }
                        val goodInfo = GoodEase(-1, -1f, "",-1f)
                        intent.putExtra("goodInfo", goodInfo as Serializable)
                        intent.putExtra("messageInfo", messagePD as Serializable)
                        startActivity(intent)
                    } else {
                        println("Failed to get user info")
                    }
                }
            })
            }

        }



    override fun onResume() {
        super.onResume()
        getMessagePreviewList()
        setAvatar(UserConst.id.toString())
        //println(UserConst.avatar)
    }

    private fun setAvatar(id : String) {
        // 头像获取
        try {
            val request = Request.Builder().url(NetworkSettings.HTTP + "/avatar/avatarGet?id=${id}")
                .get().build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (response.isSuccessful && response.body != null) {
                            UserConst.avatar = response.body?.string().toString()

                            try {
                                val decodedBytes = Base64.decode(UserConst.avatar, Base64.DEFAULT)
                                UserConst.avatarImage = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
                            } catch (e: IllegalArgumentException) {
                                e.printStackTrace()
                            }

                        } else {
                            Log.e("SERVER_ERROR", response.message)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun getMessagePreviewList() {
        val gson = Gson()
        val url = NetworkSettings.HTTP + "/message/messagePreviewGet?senderID=${UserConst.id}"
        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    val body = response.body?.string()
                    if (body == null) {
                        println("Failed to get message previews")
                        return
                    }
                    val previewList = gson.fromJson(body, Array<MessagePreviewData>::class.java).toMutableList()
                    // sender与receiver乱的，还需更改


                    activity?.runOnUiThread() {
                        if (recyclerView.adapter == null) {
                            recyclerView.adapter = MessagePreviewAdapter(getInitMessageList().toMutableList())
                        } else {
                            (recyclerView.adapter as MessagePreviewAdapter).updatePreviews(previewList)
                        }

                    }
                } else {
                    println("Failed to get message previews")
                }
            }
        })
    }


    private fun getInitMessageList(): List<MessagePreviewData> {
        // Replace with your actual data source
        var senderID = UserConst.id.toInt()

        return listOf(
            MessagePreviewData(
                senderID,
                2,
                "Hello, World",
                "https://example.com/avatar/alice.jpg",
                "Hello, World",
                "https://example.com/avatar/alice.jpg",
                "你好，世界....正在加载中",
                "",
                "2021-01-01 12:00:00",
                0
            )
        )
    }
}